//
//  QZAddMoneyVC.m
//  WeiWeiHaircut
//
//  Created by apple on 16/2/20.
//  Copyright © 2016年 超群. All rights reserved.
//

#import "QZAddMoneyVC.h"
#import "PayMoneyCell.h"
#import "QZInputMontyCell.h"


#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>


#import "WXApiRequestHandler.h"

#define PID @"2088121188856374"
#define Email @"admin@vvgufen.com"
@interface QZAddMoneyVC ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *payButon;

@end

@implementation QZAddMoneyVC{
    NSArray* titleArray;
    NSArray* infoArray;
    NSArray* imageArray;
    UIButton *selectButton;//选中的支付方式
    UITextField *_textfield;
    NSInteger _indexRow;
    NSString *_order_num;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"充值";
    
    [self addBtnOnNavWithTitle:@"钱包" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 45, 20) andDirection:left];
    [self createTableViewWithPlainStyle:NO andSeparatorStyleNone:NO andBackGroudImageName:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySour) name:@"支付成功" object:nil];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PayMoneyCell" bundle:nil] forCellReuseIdentifier:@"PayMoneyCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"QZInputMontyCell" bundle:nil] forCellReuseIdentifier:@"QZInputMontyCell"];
    [self.view bringSubviewToFront:_payButon];
    
    titleArray = @[@"支付宝支付",
                   @"微信支付",
                   @"银行卡支付"];
    
    infoArray  = @[@"推荐有支付宝的账户使用",
                   @"推荐安装微信5.0以上版本的用户使用",
                   @"支持储蓄卡信用卡无需开通网银"];
    
    imageArray = @[[UIImage imageNamed:@"zhifubao.png"],
                   [UIImage imageNamed:@"weixin.png"],
                   [UIImage imageNamed:@"中国银联.png"]];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 2;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 85;
    }else
        return 53;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    return 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        QZInputMontyCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([QZInputMontyCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _textfield = cell.inputText;
        _textfield.delegate = self;
        return cell;
    }
    PayMoneyCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PayMoneyCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 1) {
        cell.titleLabel.text    = titleArray[indexPath.row];
        cell.infoLabel.text     = infoArray[indexPath.row];
        cell.titleImage.image   = imageArray[indexPath.row];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (indexPath.section == 1 ) {
        PayMoneyCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
        selectButton.selected = NO;
        selectButton = cell.selectButton;
        selectButton.selected = YES;
        _indexRow = indexPath.row+10;
        
    }
    
    NSLog(@"indexPath.row = %ld",indexPath.row);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    return [self validateNumber:string];
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
#pragma mark- 支付按钮
- (IBAction)payMoneyTap:(UIButton *)sender {
    
    if (![_textfield.text floatValue]) {
        [[iToast makeText:@"请输入充值金额"] show];
        return;
    }
    
    if (_indexRow == 11 ||_indexRow == 10) {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Record.GetRecordAdd"];
    
    [self.request QZRequest_POST:url parameters:@{@"user_id":[QZUserInfo userId],@"money":_textfield.text} tagNSString:@"充值" stopRequest:NO isSerializer:NO isCache:NO];
    return;
    
    }


    [[iToast makeText:@"请选择付款方式"] show];
}
- (void)bizPay:(NSDictionary *)dic {
    NSString *res = [WXApiRequestHandler jumpToBizPay:dic];
    if( ![@"" isEqual:res] ){
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
    }
    
}
//支付宝支付
-(void)pay{
    NSString *partner = PID;//合作ID
    NSString *seller = Email;// 支付宝账号
    NSString *privateKey= @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAN9wj0m1KYaOHPa07B3RnIu5RWWHb8L5MyKZsjAdMkohNXGOFaRbDSl/Rde4WHeZD2HqyXO6b11c/aqOpAscKN7Ncsjwx+1h+MckBvHPuBqY4eRL6E4C126c7paSeDJP4023tkKnTkS9iqP/gMuNRZLrFdnlwW4CTAQNyXdferk7AgMBAAECgYBiWnm4SDZvND8rmZgVyB7Qok0Z0/QuLuODZ4Q4CaIJX3TW92QvZKT2jz9/JXZLruRGhcMHXhmHT1eZrBApk8uo9NfcFEnwgUYTWrI1InWVH0Yrs45MKrsZxZFB4ku4EeY/CR3l8Siu5yvI7NHS0pTq2vmZdZDx3dLXd8YVYG36gQJBAPA5LBDcP5lXbsG+gAovl3fl3aS83Xx4QRoEA4aHD67xnwltPZmmxte0jowFcJEtBkRb/ADPQ1mVUWQ7j5SnR4UCQQDuHTUeDpCTwNMx0Qk6k4US0+N/CoBY3zV052J0v6HecFM/a/TgFs7UtAGjhQN7h78y9+AIEOlbSiyIoqkebPm/AkEAglnjqXp6IFErToJ6pAxTGsJm1P+PB/2RBfbrmtIrFnkSHWFjrb6r41ychSpmfMB7yBhJ1H6jQzcdJVCUhsuGqQJANcppVnnp1UcJLsbPM+lhdYhiay+fIPSDqf4fcspbsdlkJP6pWfotDUYA3MTOrZhT7BqtBIV1ggb2moNMezAZFwJAWM5Uuw+Tb4CL/csEfR63j1CHHlTT8mP9usnskUCbll56mufrim1PuJBP9MbC7cBZ1Y85qC7wsdgYryelBCCgLQ==";//私钥
    
    
    Order *myOrder = [[Order alloc] init];
    myOrder.partner = partner;
    myOrder.seller = seller;
    
    myOrder.tradeNO = _order_num;//订单号
    myOrder.productName = @"威威商城充值";//订单标题
    myOrder.productDescription = @"威威商城充值";//订单描述，现在还没有
    myOrder.amount = _textfield.text;//金额
    myOrder.notifyURL = @"http://vv.dc125.com/vv/Public/pay/aliwap/PurseMoney.php";//预约 服务的费用
    
    
    
    
    
    NSLog(@"%@",myOrder.notifyURL);
    myOrder.service = @"mobile.securitypay.pay";
    myOrder.paymentType = @"1";
    myOrder.inputCharset = @"utf-8";
    myOrder.itBPay = @"30m";
    myOrder.showUrl = @"m.alipay.com";
    
    
    NSString *orderSpec = [myOrder description];
    
    NSLog(@"orderSpec = %@",orderSpec);
    
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    NSString *appScheme = @"weiweiHairCut";
    NSString *orderString = nil;
    
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            if ([resultDic[@"resultStatus"] integerValue] == 9000) {
                
                [[iToast makeText:@"支付成功"] show];
            }else{
                [[iToast makeText:@"支付失败"] show];
            }
            [self paySour];
        }];
    }

}

-(void)paySour{
//返回出去
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    if ([tag isEqualToString:@"充值"]) {
        
        if ([value[@"data"][@"status"] integerValue] == 100) {
            _order_num = value[@"data"][@"data"][@"order_num"];
            
            if (!_order_num) {
                [[iToast makeText:@"充值失败"] show];
                return;
            }
            if (_indexRow == 11) {//微信支付
                NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Pay.Index"];
                
                NSDictionary *dic = @{@"order_no":_order_num,
                                      @"title":@"威威商城微信支付",
                                      @"body":@"金额充值",
                                      @"price":_textfield.text,
                                      @"notify_url":@"http://vv.dc125.com/vv/Public/pay/wechat/WxPurseMoney.php"
                                      };
                [self.request QZRequest_POST:url parameters:dic tagNSString:@"微信充值" stopRequest:NO isSerializer:NO isCache:NO];
                
                return;
            }
            if (_indexRow == 10){//支付宝支付
                [self pay];
            }
            
            
        }
    }
    
    
    if ([tag isEqualToString:@"微信充值"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            NSDictionary *dic = value[@"data"][@"data"];
            [self bizPay:dic];
        }else{
            [[iToast makeText:@"充值失败"] show];
        }
        
        
    }
    
    
    
}

@end
